package com.fudan.gamestore.service.impl;

import com.fudan.gamestore.mapper.TokenMapper;
import com.fudan.gamestore.pojo.Token;
import com.fudan.gamestore.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenMapper tokenMapper;

    @Override
    public Integer insertToken(Token token) {
        return tokenMapper.insertToken(token.getToken(), token.getUserId());
    }

    @Override
    public Token getToken(String token) {
        return tokenMapper.getToken(token);
    }

    @Override
    public Integer deleteToken(String token) {
        return tokenMapper.deleteToken(token);
    }

    @Override
    public Token generateToken(Integer userId) {
        String token = UUID.randomUUID().toString();
        tokenMapper.insertToken(token, userId);
        return getToken(token);
    }

    @Override
    public int checkToken(String tokenId, Integer userId, Integer isManager) {
        if(tokenId == null)
            return -1;
        Token token = tokenMapper.getToken(tokenId);
        if(token == null)
            return -1;
        if(isManager == 1){
            if(token.getUser().getRole() == 0)//普通用户
                return -1;
        }
        else{
            if(!token.getUserId().equals(userId) && token.getUser().getRole() == 0)//普通用户验证userid是否匹配,并且该用户不是管理员
                return -1;
        }
        return 0;
    }
}
